#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <errno.h>

#define LOG_FILE "./webdav_script.log"

void log_message(const char* message) {
    FILE* log_file = fopen(LOG_FILE, "a");
    if (log_file == NULL) {
        perror("Error opening log file");
        return;
    }
    fprintf(log_file, "%s\n", message);
    fclose(log_file);
}

int main(int argc, char *argv[]) {
    if (argc != 5) {
        fprintf(stderr, "Usage: %s [mount|umount] <mount_point> <username:password> <webdav_url:port>\n", argv[0]);
        return 1;
    }

    const char* action = argv[1];
    const char* mount_point = argv[2];
    const char* credentials = argv[3];
    const char* url_port = argv[4];

    // 这里需要添加解析 credentials 和 url_port 的代码

    char secrets_file_path[] = "/root/.davfs2/secrets";
    FILE* secrets_file = fopen(secrets_file_path, "a");
    if (secrets_file == NULL) {
        perror("Error opening secrets file");
        return 1;
    }

    // 此处需要添加写入 secrets 文件的代码

    fclose(secrets_file);

    if (strcmp(action, "mount") == 0) {
        // 创建挂载点目录（如果不存在）
        char mkdir_command[256];
        sprintf(mkdir_command, "mkdir -p %s", mount_point);
        system(mkdir_command);

        // 挂载 WebDAV 网盘
        char mount_command[512];
        sprintf(mount_command, "mount -t davfs https://%s %s -o rw,uid=$(id -u),gid=$(id -g)", url_port, mount_point);
        if (system(mount_command) != 0) {
            log_message("Failed to mount WebDAV.");
            fprintf(stderr, "Failed to mount WebDAV.\n");
            return 1;
        }
    } else if (strcmp(action, "umount") == 0) {
        // 卸载 WebDAV 网盘
        char umount_command[256];
        sprintf(umount_command, "umount %s", mount_point);
        if (system(umount_command) != 0) {
            log_message("Failed to unmount WebDAV.");
            fprintf(stderr, "Failed to unmount WebDAV.\n");
            return 1;
        }
    } else {
        log_message("Invalid action.");
        fprintf(stderr, "Invalid action: %s\n", action);
        return 1;
    }

    char success_message[512];
    sprintf(success_message, "Operation %s completed for WebDAV at %s", action, mount_point);
    log_message(success_message);
    printf("%s\n", success_message);

    return 0;
}

